﻿using System;
using Microsoft.AspNetCore.Mvc;

namespace FlashPay.Management.Controllers
{
    using FlashPay.Management.Filters;
    using FlashPay.Management.ViewModels.Menu;
    using FlashPay.Management.ViewModels.User;
    using FlashPay.Entity;
    using FlashPay.Entity.Enum;
    using FlashPay.Entity.Request.User;
    using FlashPay.Entity.Response.User;
    using FlashPay.Service.Interface;
    using System.Collections.Generic;
    using System.Linq;

    public class HomeController : BaseController
    {
        /// <summary>
        /// 授权业务接口
        /// </summary>
        private readonly AuthorizeService _authorizeService;

        /// <summary>
        /// 菜单业务接口
        /// </summary>
        private readonly MenuService _menuService;

        /// <summary>
        /// 用户业务接口
        /// </summary>
        private readonly UserInfoService _userInfoService;

        /// <summary>
        /// 注入
        /// </summary>
        /// <param name="menuService"></param>
        /// <param name="authorizeService"></param>
        /// <param name="userInfoService"></param>
        public HomeController(UserDataKeepManage<UserDataKeepViewModel> _manage, AuthorizeService authorizeService, MenuService menuService, UserInfoService userInfoService) : base(_manage)
        {
            _authorizeService = authorizeService;
            _menuService = menuService;
            _userInfoService = userInfoService;
        }

        public IActionResult Index()
        {
            return View();
        }

        #region 菜单
        /// <summary>
        /// 菜单
        /// </summary>
        /// <returns></returns>
        public JsonResult GetMenu()
        {
            //输出
            var response = new JResult<List<MenuViewModel>>()
            {
                Success = false
            };

            var authorizes = _authorizeService.GetList(new Entity.Parameter.AuthorizeQuery()
            {
                UserSysNo = _manage.data.UserID,
                RoleStatus = RoleStatus.显示.GetHashCode(),
                AuthorizeType = AuthorizeType.菜单.GetHashCode()
            });

            var menuList = _menuService.GetListByIds(authorizes.Select(p => p.AuthPid).Distinct().ToList());//.Where(p => p.Status == StatusEnum.启用.GetHashCode()).ToList()
            if (menuList != null && menuList.Any())
            {
                var menus = new List<MenuViewModel>();


                var parentMenu = menuList.Where(p => p.MParent == 0).ToList();
                foreach (var itemParent in parentMenu)
                {
                    #region 子
                    var childMenus = menuList.Where(p => p.MParent == itemParent.Mid).ToList();

                    var childMenuList = new List<ChildMenu>();

                    foreach (var itemChild in childMenus)
                    {
                        childMenuList.Add(new ChildMenu()
                        {
                            Id = itemChild.Mid,
                            Name = itemChild.MName,
                            Url = itemChild.MUrl
                        });
                    }
                    #endregion

                    menus.Add(new MenuViewModel()
                    {
                        Id = itemParent.Mid,
                        Name = itemParent.MName,
                        Url = itemParent.MUrl,
                        childMenus = childMenuList
                    });

                }
                response.Success = true;
                response.Data = menus;
            }

            return Json(response);
        }
        #endregion

        #region 修改密码
        /// <summary>
        /// 修改
        /// </summary>
        /// <returns></returns>
        public JsonResult getUser()
        {
            //输出
            var response = new JResult<UserInfoResponse>()
            {
                Success = false
            };

            try
            {
                var userInfo = _userInfoService.Get(_manage.data.UserID);
                if (userInfo != null)
                {
                    response.Success = true;
                    response.Data = new UserInfoResponse()
                    {
                        UserName = userInfo.ULoginName
                    };
                }
            }
            catch (Exception ex)
            {
                response.ErrorMessage = ex.Message;
            }

            return Json(response);
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        public JsonResult EditPassWord(UpdatePassWordViewModel request)
        {
            //输出
            var response = new JResult()
            {
                Success = false
            };

            if (!ModelState.IsValid)
            {
                var message = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage).FirstOrDefault();
                response.Success = false;
                response.ErrorMessage = message;
                return Json(response);
            }

            var updatePassWordPara = new UpdatePassWordRequest()
            {
                Id = _manage.data.UserID,
                OldPassword = request.OldPassword,
                NewPassword = request.NewPassword,
                ConfirmNewPassword = request.ConfirmNewPassword
            };
            response = _userInfoService.UpdatePassWord(updatePassWordPara);
            return Json(response);
        }
        #endregion

        //[HttpGet]
        //public IActionResult Export()
        //{
        //    string sWebRootFolder = "d://";
        //    string sFileName = $@"qmhuangtext{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
        //    var path = Path.Combine(sWebRootFolder, sFileName);
        //    FileInfo file = new FileInfo(path);
        //    //构建数据
        //    List<Person> list1 = new List<Person>()
        //        {
        //            new Person{Name = "123",Sex="男"},
        //            new Person{Name = "234",Sex="男"},
        //            new Person{Name = "345",Sex="女"}
        //        };
        //    if (file.Exists)
        //    {
        //        file.Delete();
        //        file = new FileInfo(path);
        //    }
        //    using (ExcelPackage package = new ExcelPackage(file))
        //    {
        //        //创建sheet
        //        ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("sheetname");
        //        worksheet.Cells.LoadFromCollection(list1, true);
        //        package.Save();
        //    }
        //    return File(new FileStream(Path.Combine(sWebRootFolder, sFileName), FileMode.Open), "application/octet-stream", $"excel导出测试{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx");
        //}

        ///// <summary>
        ///// 读取sheet 内的数据进入实体
        ///// </summary>
        ///// <param name="worksheet"></param>
        ///// <returns></returns>
        //public List<Person> GetSheetValues(string filepath)
        //{
        //    FileInfo file = new FileInfo(filepath);
        //    if (file != null)
        //    {
        //        using (ExcelPackage package = new ExcelPackage(file))
        //        {

        //            ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
        //            //获取表格的列数和行数
        //            int rowCount = worksheet.Dimension.Rows;
        //            int ColCount = worksheet.Dimension.Columns;
        //            var persons = new List<Person>();
        //            for (int row = 1; row <= rowCount; row++)
        //            {
        //                Person person = new Person();
        //                person.Name = worksheet.Cells[row, 1].Value.ToString();
        //                person.Sex = worksheet.Cells[row, 2].Value.ToString();
        //                persons.Add(person);
        //            }
        //            return persons;
        //        }
        //    }
        //    return null;
        //}
    }
}
